package com.example.wxchatdemo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class socketActivity extends AppCompatActivity {

    private Context mContext;
    private TextView show;
    private EditText text2;
    private Button sent;
    private Button close;
    private Button connect;
    private Socket socket;
    private PrintWriter printWriter;
    private  int isno;
    BufferedReader bufferedReader = null;
    private socketAdapter socketAdapter;
    private ListView listViews;
    private List<socketAdapter> list;
    private int action;
    /**
     * 主 变量
     */

    // 主线程Handler
    // 用于将从服务器获取的消息显示出来
    private Handler mMainHandler;


    // 线程池
    // 为了方便展示,此处直接采用线程池进行线程管理,而没有一个个开线程
    private ExecutorService mThreadPool;

    /**
     * 接收服务器消息 变量
     */
    // 输入流对象
    InputStream is;

    // 输入流读取器对象
    InputStreamReader isr ;
    BufferedReader br ;

    // 接收服务器发送过来的消息
    String response;


    /**
     * 发送消息到服务器 变量
     */
    // 输出流对象
    OutputStream outputStream;

    /**
     * 按钮 变量
     */

    // 连接 断开连接 发送数据到服务器 的按钮变量
    private Button btnConnect, btnDisconnect, btnSend;



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_socket);
        mContext = socketActivity.this;
        sent=(Button) findViewById(R.id.sentss);
        close=(Button) findViewById(R.id.close);
        connect=(Button) findViewById(R.id.connect);

        listViews=(ListView) findViewById(R.id.listviewss);
        text2  = (EditText)findViewById(R.id.text2);
        show=(TextView)findViewById(R.id.show);
        //线程池
        mThreadPool = Executors.newCachedThreadPool();
//创建连接
       new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket("100.2.33.224", 8086);
                    isno=1;
                    ///*****
                    System.out.println("开启了读写模式");
                    try {

                        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        String msg;//服务器发过来的信息
                        while ((msg = bufferedReader.readLine()) != null) {
                            System.out.println("##=====服务器发送信息是：" + msg);
                            //
                            String finalMsg = msg;
                            //修改当前的ui
                            socketActivity.this.runOnUiThread(new Runnable() {
                                public void run() {
                                    show.setTextSize(20);
                                    show.setText(finalMsg);
                                  //  listViews.setAdapter(new socketAdapter(mContext,finalMsg));

                                }
                            });
                            //

                        }
                        System.out.println("你偷懒啊=====");
                    } catch (IOException e) {
                        System.out.println("警告：断开连接！");
                        try {
                            if (!socket.isClosed()) {
                                socket.close();
                            }
                        } catch (IOException e1) {
                            System.out.println("读取线程：关闭socket出现错误");
                        }
                    }
                   // System.exit(1);
                    System.out.println("中心");

                    ////***

                } catch (IOException e) {
                    System.out.println("socket线程出错了");
                    isno=0;
                }//
            }
        }).start();








/*宇康程序
connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 利用线程池直接开启一个线程 & 执行该线程
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            // 创建Socket对象 & 指定服务端的IP 及 端口号
                            socket = new Socket("100.2.33.224", 9999);

                            // 判断客户端和服务器是否连接成功
                            System.out.println("连接"+socket.isConnected());

                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });

            }
        });
sent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 利用线程池直接开启一个线程 & 执行该线程
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            // 步骤1：从Socket 获得输出流对象OutputStream
                            // 该对象作用：发送数据
                            outputStream = socket.getOutputStream();

                            // 步骤2：写入需要发送的数据到输出流对象中
                            outputStream.write((text2.getText().toString()+"\n").getBytes("utf-8"));
                            // 特别注意：数据的结尾加上换行符才可让服务器端的readline()停止阻塞

                            // 步骤3：发送数据到服务端
                            outputStream.flush();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });

            }
        });
close.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        // 利用线程池直接开启一个线程 & 执行该线程
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {

                try {
                    while (true){
                        // 步骤1：创建输入流对象InputStream
                        is = socket.getInputStream();

                        // 步骤2：创建输入流读取器对象 并传入输入流对象
                        // 该对象作用：获取服务器返回的数据
                        isr = new InputStreamReader(is);
                        br = new BufferedReader(isr);

                        while (true) {                                      //步骤三
                            if ((response = br.readLine()) != null) {

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        System.out.println("接收的消息是==="+response);
                                        show.setText(show.getText() + "\n\n" + response);
                                    }
                                });
                            }
                        }

                    }
//                                // 步骤3：通过输入流读取器对象 接收服务器发送过来的数据
//                                response = br.readLine();
//
//                                // 步骤4:通知主线程,将接收的消息显示到界面
//                                Message msg = Message.obtain();
//                                msg.what = 0;
//                                mMainHandler.sendMessage(msg);


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

    }
});
*/


        //提交ann
        sent.setOnClickListener(new View.OnClickListener() {
            //
            @Override
            public void onClick(View view) {
                String msgs=text2.getText().toString();
//*****
                    mThreadPool.execute(new Runnable() {


                        @Override
                        public void run() {
                            if (0!=isno) {

                                try {
                                    printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
                                } catch (IOException e) {
                                    System.out.println("链接已断开发送消息");
                                }
                                printWriter.println(msgs);

                                System.out.println("发送消息成功----"+msgs);
                                if (msgs.equals("88")){
                                    try {
                                        socket.close();
                                        isno=2;
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            else {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            socket = new Socket("100.2.33.224", 8086);
                                            isno=1;
                                        } catch (IOException e) {
                                            System.out.println("socket线程出错了");
                                            isno=0;
                                        }//
                                    }
                                }).start();

                            }
                        }
                    });
//----
            }
//*******


                //跳转页面


        });
        //关闭按钮
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    socket.close();
                    System.out.println("链接已关闭了socket");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
        //连接按钮
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {



                //
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            socket = new Socket("100.2.33.224", 8086);
                            isno=1;
                            ///*****
                            System.out.println("开启了读写模式");
                            try {

                                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                String msg;//服务器发过来的信息
                                while ((msg = bufferedReader.readLine()) != null) {
                                    System.out.println("##=====服务器发送信息是：" + msg);
                                    //
                                    String finalMsg = msg;
                                    //修改当前的ui
                                    socketActivity.this.runOnUiThread(new Runnable() {
                                        public void run() {
                                            show.setTextSize(20);
                                            show.setText(finalMsg);
                                            //  listViews.setAdapter(new socketAdapter(mContext,finalMsg));

                                        }
                                    });
                                    //

                                }
                                System.out.println("你偷懒啊=====");
                            } catch (IOException e) {
                                System.out.println("警告：断开连接！");
                                try {
                                    if (!socket.isClosed()) {
                                        socket.close();
                                    }
                                } catch (IOException e1) {
                                    System.out.println("读取线程：关闭socket出现错误");
                                }
                            }
                            // System.exit(1);
                            System.out.println("中心");

                            ////***

                        } catch (IOException e) {
                            System.out.println("socket线程出错了");
                            isno=0;
                        }//
                    }
                });

            }
        });




}
}
